<?php
/**
 * 题目链接 https://leetcode.cn/problems/pascals-triangle-ii/description/
 */

class Solution {

    /**
     * 利用递归来解决问题
     * @param int $rowIndex
     * @return int[]
     */
    public static function getRow1(int $rowIndex): array 
    {
        if ($rowIndex == 0) {
            return [1];
        } elseif ($rowIndex == 1) {
            return [1, 1];
        } else {
            $result = [1];
            $pre = self::getRow($rowIndex - 1);
            for ($i=1; $i < count($pre); $i++) { 
                $result[] = $pre[$i - 1] + $pre[$i];
            }
        }
        $result[] = 1;

        return $result;
    }

    /**
     * 优化递归
     * @param int $rowIndex
     * @return int[]
     */
    public static function getRow(int $rowIndex): array 
    {
        if (isset($res[$rowIndex])) {
            return $res[$rowIndex];
        }
        if ($rowIndex == 0) {
            $res[$rowIndex] = [1];
            return $res[$rowIndex];
        } elseif ($rowIndex == 1) {
            $res[$rowIndex] = [1, 1];
            return $res[$rowIndex];
        } else {
            $result = [1];
            $pre = self::getRow($rowIndex - 1);
            for ($i=1; $i < count($pre); $i++) { 
                $result[] = $pre[$i - 1] + $pre[$i];
            }
        }
        $result[] = 1;
        $res[$rowIndex] = $result;

        return $res[$rowIndex];
    }
}

$test = [
    [0],
    [4],
    [3],
    [6],
];
$result = [
    [1],
    [1,4,6,4,1],
    [1,3,3,1],
    [1,6,15,20,15,6,1],
];

foreach ($test as $key => $value) {
    $r = Solution::getRow($value[0]);
    if ($r !== $result[$key]) {
        echo sprintf("第%d个case不通过", $key) . PHP_EOL;
    }
    print_r($r);
}